package com.party.mobile.web.controller.mall;

import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Maps;
import com.party.authorization.annotation.Authorization;
import com.party.common.paging.Page;
import com.party.common.utils.PartyCode;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.YesNoStatus;
import com.party.core.model.commune.CMemberIntegralCount;
import com.party.core.model.mall.*;
import com.party.core.model.order.OrderForm;
import com.party.core.model.order.OrderStatus;
import com.party.core.model.system.TargetType;
import com.party.core.service.commune.ICMemberIntegralCountService;
import com.party.core.service.mall.IMallEvaluateService;
import com.party.core.service.mall.IMallGoodsService;
import com.party.core.service.mall.IMallOrderDetailService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.order.IOrderFormService;
import com.party.mobile.biz.currentUser.CurrentUserBizService;
import com.party.mobile.biz.mall.MallOrderBizService;
import com.party.mobile.web.annotation.VisitCollect;
import com.party.mobile.web.dto.AjaxResult;
import com.party.mobile.web.dto.login.output.CurrentUser;
import com.party.mobile.web.dto.mall.input.MallOrderInput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @Author: Administrator.
 * @Description: 商城订单管理
 * @Date:Created in 2017/8/30 0030 下午 19:03.
 */
@Controller
@RequestMapping("mall/order")
public class MallOrderController {

    @Autowired
    private CurrentUserBizService currentUserBizService;
    @Autowired
    private IOrderFormService orderFormService;
    @Autowired
    private MallOrderBizService mallOrderBizService;
    @Autowired
    private IMallEvaluateService mallEvaluateService;
    @Autowired
    private IMallOrderDetailService mallOrderDetailService;
    @Autowired
    private IMallGoodsService mallGoodsService;
    @Autowired
    private IMemberGroupService memberGroupService;
    @Autowired
    private ICMemberIntegralCountService memberIntegralCountService;


    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 订单列表
     *
     * @param status 状态
     * @param page   分页参数
     * @return
     */
    @Authorization
    @ResponseBody
    @RequestMapping("list")
    @VisitCollect(module = TargetType.MALL)
    public AjaxResult list(Integer status, Page page, HttpServletRequest request) {
        try {
            CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
            List<MallOrderOutputPay> orderOutputs = mallOrderBizService.getOrderList(status, currentUser.getId(), page);
            return AjaxResult.success(orderOutputs, page);
        } catch (Exception e) {
            logger.error("订单列表异常", e);
            return AjaxResult.error(100, "订单列表异常");
        }
    }

    /**
     * 订单详情
     *
     * @param orderId 支付订单id
     * @param disId   分销者id
     * @return
     */
    @ResponseBody
    @Authorization
    @RequestMapping("getDetail")
    @VisitCollect(module = TargetType.MALL)
    public AjaxResult getDetail(String orderId, String disId, HttpServletRequest request) {
        if (StringUtils.isEmpty(orderId)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "主订单id不能为空");
        }

        try {
            CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
            if (null != currentUser.getIsMemberGroup() && YesNoStatus.YES.getCode().equals(currentUser.getIsMemberGroup())) {
                disId = memberGroupService.getPartnerId(disId);
            }
            Map<String, Object> resultMap = mallOrderBizService.getOrderDetail(orderId, disId, currentUser.getId());
            return AjaxResult.success(resultMap);
        } catch (BusinessException e) {
            return AjaxResult.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("订单详情异常", e);
            return AjaxResult.error(100, "订单详情异常");
        }
    }

    /**
     * 结算
     *
     * @param orderInput
     * @param request
     * @return
     */
    @ResponseBody
    @Authorization
    @RequestMapping(value = "buyOrder", method = RequestMethod.POST)
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult buyOrder(MallOrderInput orderInput, BindingResult result, HttpServletRequest request) {
        try {
            if (result.hasErrors()) {
                List<ObjectError> allErrors = result.getAllErrors();
                String description = allErrors.get(0).getDefaultMessage();
                return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, description);
            }
            if (StringUtils.isEmpty(orderInput.getBuyParams())) {
                return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "结算参数异常");
            }
            List<Map<String, Object>> buyProducts = JSONArray.parseObject(orderInput.getBuyParams(), List.class);
            if (buyProducts.size() == 0) {
                return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "结算参数异常");
            }
            CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
            Map<String, Object> resultMap = mallOrderBizService.buyOrder(currentUser.getId(), orderInput, buyProducts);
            return AjaxResult.success(resultMap);
        } catch (BusinessException e) {
            logger.error("结算异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("结算异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(110, e.getMessage());
        }
    }

    /**
     * 单个商品申请退款
     *
     * @param id 子订单id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "singleApplyRefund", method = RequestMethod.POST)
    public AjaxResult singleApplyRefund(String id) {
        if (StringUtils.isEmpty(id)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "id不能为空");
        }
        try {
            mallOrderBizService.applyRefund(id);
            return AjaxResult.success();
        } catch (BusinessException e) {
            logger.error("申请退款异常", e);
            return AjaxResult.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("申请退款异常", e);
            return AjaxResult.error(1100, e.getMessage());
        }
    }

    /**
     * 收到退款 子订单状态改为 已退款，如果全部的子订单都是已退款，则主订单状态为已关闭
     *
     * @param orderDetailId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "receiveRefund", method = RequestMethod.POST)
    public AjaxResult receiveRefund(String orderDetailId) {
        if (StringUtils.isEmpty(orderDetailId)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "id不能为空");
        }

        try {
            MallOrderDetail orderDetail = mallOrderDetailService.get(orderDetailId);
            orderDetail.setStatus(MallOrderDetailStatus.STATUS_REFUND_SUCCESS.getCode()); // 已退款
            mallOrderDetailService.update(orderDetail);

            boolean flag = false;
            MallOrderDetail search = new MallOrderDetail();
            search.setParentId(orderDetail.getParentId());
            List<MallOrderDetail> orderDetails = mallOrderDetailService.list(search);
            for (MallOrderDetail od : orderDetails) {
                if (od.getStatus().equals(MallOrderDetailStatus.STATUS_REFUND_SUCCESS.getCode())) {
                    flag = true;
                } else {
                    flag = false;
                }
            }

            if (flag) {
                MallOrderDetail parent = mallOrderDetailService.get(orderDetail.getParentId());
                parent.setStatus(MallOrderDetailStatus.STATUS_CLOSED.getCode());
                mallOrderDetailService.update(parent);

                OrderForm orderForm = orderFormService.get(parent.getOrderId());
                orderForm.setStatus(OrderStatus.ORDER_STATUS_REFUND.getCode());
                orderFormService.update(orderForm);
            }
        } catch (Exception e) {
            logger.error("退款异常：{}", e);
            return AjaxResult.error(1100, e.getMessage());
        }
        return AjaxResult.success();
    }

    /**
     * 取消订单
     *
     * @param orderId 支付订单id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "cancel", method = RequestMethod.POST)
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult cancel(String orderId) {
        if (StringUtils.isEmpty(orderId)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "id不能为空");
        }

        try {
            mallOrderBizService.cancel(orderId);
            return AjaxResult.success();
        } catch (BusinessException e) {
            logger.error("取消订单异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("取消订单异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(11000, "取消订单异常");
        }
    }

    /**
     * 删除订单
     *
     * @param orderId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public AjaxResult delete(String orderId) {
        if (StringUtils.isEmpty(orderId)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "id不能为空");
        }

        try {
            mallOrderBizService.delete(orderId);
            return AjaxResult.success();
        } catch (BusinessException e) {
            logger.error("删除订单异常", e);
            return AjaxResult.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("删除订单异常", e);
            return AjaxResult.error(11000, "删除订单异常");
        }
    }

    /**
     * 确认收货
     *
     * @param orderId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "receiveShipment", method = RequestMethod.POST)
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult receiveShipment(String orderId) {
        if (StringUtils.isEmpty(orderId)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "订单id不能为空");
        }
        try {
            mallOrderBizService.receiveShipment(orderId);
            return AjaxResult.success();
        } catch (BusinessException e) {
            logger.error("确认收货异常", e);
            return AjaxResult.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("确认收货异常", e);
            return AjaxResult.error(11000, "确认收货异常");
        }
    }

    /**
     * 评价
     *
     * @param orderId
     * @param evaluateJson
     * @return
     */
    @ResponseBody
    @Authorization
    @RequestMapping("saveEvaluate")
    public AjaxResult saveEvaluate(String orderId, String evaluateJson, HttpServletRequest request) {
        if (StringUtils.isEmpty(orderId)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "订单id不能为空");
        }
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        List<MallEvaluate> evaluates = JSONArray.parseArray(evaluateJson, MallEvaluate.class);
        for (MallEvaluate evaluate : evaluates) {
            evaluate.setOrderId(orderId);
            evaluate.setUpdateBy(currentUser.getId());
            mallEvaluateService.insert(evaluate);
        }


//        List<MallOrderDetail> orderDetails = mallOrderDetailService.newListPage(new MallOrderDetail(orderId), null, null);
//        for (MallOrderDetail orderDetail : orderDetails) {
//            for (MallOrderDetail c : orderDetail.getChildrens()) {
//                c.setStatus(MallOrderDetailStatus.STATUS_COMPLETE.getCode());
//                mallOrderDetailService.update(c);
//            }
//            orderDetail.setStatus(MallOrderDetailStatus.STATUS_COMPLETE.getCode());
//            mallOrderDetailService.update(orderDetail);
//        }
        return AjaxResult.success();
    }

    /**
     * 商品评价列表
     *
     * @param type
     * @param goodsId
     * @param page
     * @return
     */
    @ResponseBody
    @RequestMapping("evaluateList")
    public AjaxResult evaluateList(String type, String goodsId, Page page) {
        if (StringUtils.isEmpty(goodsId)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "商品id不能为空");
        }

        Map<String, Object> params = Maps.newHashMap();
        params.put("goodsId", goodsId);
        if (type.equals("-1")) { // 全部

        } else if (type.equals("1")) { // 最新

        } else if (type.equals("2")) { // 好评
            params.put("level", MallEvaluate.LEVEL_GOOD);
        } else if (type.equals("3")) { // 中评
            params.put("level", MallEvaluate.LEVEL_ZHONG);
        } else if (type.equals("4")) { // 差评
            params.put("level", MallEvaluate.LEVEL_BAD);
        } else if (type.equals("5")) { // 有图
            params.put("hasPic", true);
        }

        List<MallEvaluateListOutput> outputs = mallEvaluateService.newListPage(params, page);
        for (MallEvaluateListOutput output : outputs) {
            if (StringUtils.isNotEmpty(output.getPic())) {
                output.setPicList(output.getPic().split(","));
            }
        }

        MallGoods mallGoods = mallGoodsService.get(goodsId);

        Map<String, Object> countMap = mallOrderBizService.getCount(goodsId);
        Map<String, Object> resultMap = Maps.newHashMap();
        resultMap.putAll(countMap);
        resultMap.put("type", type);
        resultMap.put("evaluates", outputs);
        resultMap.put("mallGoods", mallGoods);
        return AjaxResult.success(resultMap, page);
    }

    /**
     * 购买页
     *
     * @param cartIds   购物车记录IDS abc,abc,abc
     * @param buyParams 购买参数 {"productId": abc, "quantity": 10, "distributorId": ""}
     * @param request
     * @return
     */
    @ResponseBody
    @Authorization
    @RequestMapping("buyDetail")
    public AjaxResult buyDetail(String cartIds, String buyParams, HttpServletRequest request) {
        if (StringUtils.isEmpty(cartIds) && StringUtils.isEmpty(buyParams)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "参数不能为空");
        }
        try {
            CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
            Map<String, Object> result = mallOrderBizService.getBuyDetail(cartIds, buyParams, currentUser.getId());
            return AjaxResult.success(result);
        } catch (Exception e) {
            logger.error("获取购买详情异常", e);
            return AjaxResult.error(100, "获取购买详情异常");
        }
    }

    /**
     * 我的分销订单列表
     *
     * @param status  状态
     * @param request
     * @param page
     * @return
     */
    @ResponseBody
    @Authorization
    @RequestMapping("getDistributorOrderList")
    public AjaxResult getDistributorOrderList(Integer status, HttpServletRequest request, Page page) {
        try {
            CurrentUser currentUser = currentUserBizService.getCurrentUser(request);

            String memberId = memberGroupService.getPartnerId(currentUser.getId());

            List<MallOrderOutputPay> orderOutputs = mallOrderBizService.getDistributorOrderList(status, memberId, page);
            return AjaxResult.success(orderOutputs, page);
        } catch (Exception e) {
            logger.error("获取我的分销订单列表异常", e);
            return AjaxResult.error(100, "获取我的分销订单列表异常");
        }
    }

    /**
     * 我的收入订单
     *
     * @param startDate 自定义开始日期
     * @param endDate   自定义结束日期
     * @param request
     * @param page
     * @return
     */
    @ResponseBody
    @Authorization
    @RequestMapping("getRevenueOrderList")
    public AjaxResult getRevenueOrderList(String startDate, String endDate, HttpServletRequest request, Page page) {
        try {
//            if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
//                return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "日期不能为空");
//            }
            CurrentUser currentUser = currentUserBizService.getCurrentUser(request);

            String memberId = memberGroupService.getPartnerId(currentUser.getId());

            List<MallOrderOutputPay> orderOutputs = mallOrderBizService.getRevenueOrderList(startDate, endDate, memberId, page);
            return AjaxResult.success(orderOutputs, page);
        } catch (Exception e) {
            logger.error("获取我的分销订单列表异常", e);
            return AjaxResult.error(100, "获取我的分销订单列表异常");
        }
    }


    /**
     * 我的收入数据
     *
     * @param startDate 自定义开始日期
     * @param endDate   自定义结束日期
     * @param request
     * @return
     */
    @ResponseBody
    @Authorization
    @RequestMapping("getRevenueData")
    public AjaxResult getRevenueData(String startDate, String endDate, HttpServletRequest request) {
        try {
//            if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
//                return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "日期不能为空");
//            }
            CurrentUser currentUser = currentUserBizService.getCurrentUser(request);

            String memberId = memberGroupService.getPartnerId(currentUser.getId());

            Map<String, Object> revenueData = mallOrderBizService.getRevenueData(startDate, endDate, memberId);
            return AjaxResult.success(revenueData);
        } catch (Exception e) {
            logger.error("获取我的收入数据异常", e);
            return AjaxResult.error(100, "获取我的收入数据异常");
        }
    }

    /**
     * 获取我的今日收入数据
     *
     * @param request
     * @return
     */
    @ResponseBody
    @Authorization
    @RequestMapping("getTodayRevenueData")
    public AjaxResult getTodayRevenueData(HttpServletRequest request) {
        try {
            CurrentUser currentUser = currentUserBizService.getCurrentUser(request);

            String memberId = memberGroupService.getPartnerId(currentUser.getId());

            Map<String, Object> revenueData = mallOrderBizService.getTodayRevenueData(memberId);
            return AjaxResult.success(revenueData);
        } catch (Exception e) {
            logger.error("获取我的今日收入数据异常", e);
            return AjaxResult.error(100, "获取我的今日收入数据异常");
        }
    }

    /**
     * 订单详情
     *
     * @param orderId
     * @param request
     * @return
     */
    @ResponseBody
    @Authorization
    @RequestMapping("getOrderInfo")
    public AjaxResult getOrderInfo(String orderId, HttpServletRequest request) {
        try {
            CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
            String disId = memberGroupService.getPartnerId(currentUser.getId());
            MallOrderOutputPay revenueData = mallOrderBizService.getOrderInfo(disId, orderId);
            return AjaxResult.success(revenueData);
        } catch (Exception e) {
            logger.error("获取我的今日收入数据异常", e);
            return AjaxResult.error(100, "获取我的今日收入数据异常");
        }
    }


    /**
     * 获取用户积分
     *
     * @param request
     * @return
     */
    @ResponseBody
    @Authorization
    @RequestMapping("getUserIntegral")
    public AjaxResult getUserIntegral(HttpServletRequest request) {
        try {
            CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
            CMemberIntegralCount memberIntegralCount = memberIntegralCountService.getByMemberId(currentUser.getId());
            Double availableIntegral = 0d;
            if (memberIntegralCount != null) {
                availableIntegral = memberIntegralCount.getAvailableIntegral();
            }
            return AjaxResult.success(availableIntegral);
        } catch (Exception e) {
            logger.error("获取我的今日收入数据异常", e);
            return AjaxResult.error(100, "获取我的今日收入数据异常");
        }
    }
}
